/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     https://yiyuery.github.io/
 * @date:        2019/5/20 20:57
 * @email:       xiazhaoyang@live.com
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.common.spring.security;

import com.example.common.spring.config.CapPropertyPlaceholderConfigurer;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PBEStringCleanablePasswordEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-07-28 14:13
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-07-28
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Slf4j
public class CapLazyEncryptor implements StringEncryptor {

    private static PBEStringCleanablePasswordEncryptor singleton;

    private static CapPropertyPlaceholderConfigurer configurer;

    public static synchronized PBEStringCleanablePasswordEncryptor getSingleton(final Environment e, final BeanFactory bf) {
        if (Objects.isNull(singleton)) {
            singleton = createDefault(e, bf);
        }
        return singleton;
    }

    private CapLazyEncryptor() {
    }

    private static PBEStringCleanablePasswordEncryptor createDefault(Environment e, BeanFactory bf) {
        configurer = bf.getBean(CapPropertyPlaceholderConfigurer.class);
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(getRequiredProperty(e, "jasypt.encryptor.password"));
        config.setAlgorithm(getProperty(e, "jasypt.encryptor.algorithm", "PBEWithMD5AndDES"));
        config.setKeyObtentionIterations(getProperty(e, "jasypt.encryptor.keyObtentionIterations", "1000"));
        config.setPoolSize(getProperty(e, "jasypt.encryptor.poolSize", "1"));
        config.setProviderName(getProperty(e, "jasypt.encryptor.providerName", null));
        config.setProviderClassName(getProperty(e, "jasypt.encryptor.providerClassName", null));
        config.setSaltGeneratorClassName(getProperty(e, "jasypt.encryptor.saltGeneratorClassname", "org.jasypt.salt.RandomSaltGenerator"));
        config.setStringOutputType(getProperty(e, "jasypt.encryptor.stringOutputType", "base64"));
        encryptor.setConfig(config);
        return encryptor;
    }

    private static String getProperty(Environment environment, String key, String defaultValue) {
        if (!propertyExists(environment, key)) {
            log.info("Encryptor config not found for property {}, using default value: {}", key, defaultValue);
        }
        String property = environment.getProperty(key);
        return Objects.isNull(property) ? configurer.getCapProps().getProperty(key, defaultValue) : property;
    }

    private static boolean propertyExists(Environment environment, String key) {
        return environment.getProperty(key) != null || configurer.getCapProps().getProperty(key) != null;
    }

    private static String getRequiredProperty(Environment environment, String key) {
        if (!propertyExists(environment, key)) {
            throw new IllegalStateException(String.format("Required Encryption configuration property missing: %s", key));
        }
        String property = environment.getProperty(key);
        return Objects.isNull(property) ? configurer.getCapProps().getProperty(key) : property;
    }

    /**
     * Encrypt the input message
     *
     * @param message the message to be encrypted
     * @return the result of encryption
     */
    @Override
    public String encrypt(String message) {
        return singleton.encrypt(message);
    }

    /**
     * Decrypt an encrypted message
     *
     * @param encryptedMessage the encrypted message to be decrypted
     * @return the result of decryption
     */
    @Override
    public String decrypt(String encryptedMessage) {
        return singleton.decrypt(encryptedMessage);
    }
}
